package com.timmy.google_play.fragment;

import android.os.SystemClock;
import android.view.View;
import android.widget.ListView;

import com.timmy.google_play.base.BaseFragment;
import com.timmy.google_play.base.ItemAdapter;
import com.timmy.google_play.base.ListViewFactory;
import com.timmy.google_play.base.LoadingPager;
import com.timmy.google_play.bean.ItemBean;
import com.timmy.google_play.holder.ItemHolder;
import com.timmy.google_play.manager.DownLoadInfo;
import com.timmy.google_play.manager.DownLoadManager;
import com.timmy.google_play.protocol.GameProtocol;

import java.util.List;

/**
 * Created by Timmy on 2016/12/7.
 * <p>
 * 首页
 */

public class GameFragment extends BaseFragment {

    private GameProtocol   mGameProtocol;
    private List<ItemBean> mDatas;
    private GameAdapter mAdapter;

    @Override
    protected LoadingPager.LoadedResult initData() {


        mGameProtocol = new GameProtocol();
        try {
            mDatas = mGameProtocol.loadData(0);
            return checkResData(mDatas);
        } catch (Exception e) {
            e.printStackTrace();
            return LoadingPager.LoadedResult.ERROR;
        }
    }

    @Override
    protected View initSuccessView() {
        ListView listView = ListViewFactory.createListView();

        mAdapter = new GameAdapter(listView, mDatas);
        listView.setAdapter(mAdapter);

        return listView;
    }

    class GameAdapter extends ItemAdapter {

        public GameAdapter(ListView listView, List<ItemBean> datas) {
            super(listView, datas);
        }

        @Override
        public List<ItemBean> onLoadMoreData() throws Exception {
            SystemClock.sleep(1200);

            List<ItemBean> itemBeen = mGameProtocol.loadData(mDatas.size());

            return itemBeen;
        }
    }

    @Override
    public void onResume() {
        //添加观察者
        if (mAdapter != null) {

            List<ItemHolder> itemHolders = mAdapter.getItemHolders();

            for (ItemHolder itemHolder : itemHolders) {
                DownLoadManager.getInstance().addObserver(itemHolder);

                //手动发布最新的状态信息
                //1.得到最新的downloadinfo信息
                DownLoadInfo downLoadInfo = DownLoadManager.getInstance().getDownLoadInfo(itemHolder.mData);

                //2.发布最新消息
                DownLoadManager.getInstance().notifyObserver(downLoadInfo);

            }
        }


        super.onResume();
    }

    @Override
    public void onPause() {
        //移除观察者
        if (mAdapter != null) {

            List<ItemHolder> itemHolders = mAdapter.getItemHolders();

            for (ItemHolder itemHolder : itemHolders) {
                DownLoadManager.getInstance().deleteObserver(itemHolder);
            }
        }

        super.onPause();
    }
}
